from pydantic import BaseModel

# coding: utf-8
from sqlalchemy import Column, DateTime, Integer, String, text, event
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from sqlalchemy.sql import func
from typing import Optional

Base = declarative_base()
metadata = Base.metadata


class File(Base):
    def to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    __tablename__ = 'files'

    id = Column(Integer, primary_key=True, comment='主键ID')
    user_type = Column(Integer, nullable=False, comment='上传者类型，1 管理员 2 用户')
    user_id = Column(Integer, nullable=False, comment='对应用户id')
    file_url = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False, comment='文件URL')
    type = Column(String(50, 'utf8mb4_unicode_ci'), nullable=False, comment='存储方式，local, oss, qiniu')
    file_type = Column(Integer, nullable=False, comment='文件类型，1 Excel 2 CSV')
    name = Column(String(255, 'utf8mb4_unicode_ci'), nullable=False, comment='文件名字')
    ext = Column(String(50, 'utf8mb4_unicode_ci'), nullable=False, comment='扩展名')
    file_size = Column(Integer, comment='文件大小')
    deleted_at = Column(DateTime(timezone=True), nullable=True, comment='删除时间')
    created_at = Column(DateTime, server_default=func.now(), comment='创建时间')
    updated_at = Column(DateTime, onupdate=func.now(), comment='更新时间')

@event.listens_for(File, 'before_update')
def receive_before_update(mapper, connection, target):
    target.updated_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")

@event.listens_for(File, 'before_insert')
def set_created_at(mapper, connection, target):
    if not target.created_at:
        target.created_at = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M")


class FileSchema(BaseModel):
    id: int
    user_type: int
    user_id: int
    file_url: str
    type: str
    file_type: int
    name: str
    ext: str
    file_size: int
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None
    deleted_at: Optional[datetime] = None

    class Config:
        orm_mode = True
        json_encoders = {
            datetime: lambda v: v.strftime('%Y-%m-%d %H:%M:%S') if v else None
        }
        from_attributes = True

